package team.common.utility;

import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.view.AbstractView;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class JsonView extends AbstractView 
{
	@SuppressWarnings("unchecked")
	@Override  
	protected void renderMergedOutputModel(Map map,HttpServletRequest request,HttpServletResponse response) throws Exception 
	{
		boolean isArray = false;
		
		//get the model from the map passed created by the controller
		Object model = null;
		 
		model = map.get("AJAX_MODEL");
		
		//if the model is null, we have an exception
		JSONObject jsonObject = null;
		JSONArray  jsonArray =  null;
//		jakarta commons-lang 2.4 
//		jakarta commons-beanutils 1.7.0 
//		jakarta commons-collections 3.2 
//		jakarta commons-logging 1.1.1 
//		ezmorph 1.0.6  
		if (model != null) 
		{
			if (model instanceof java.util.List) 
			{ 
				isArray = true;
				jsonArray = JSONArray.fromObject( model );
			}
			else 
			{
				jsonObject = JSONObject.fromObject( model );   
			}
		} 
		else 
		{
			// so render entire map
			jsonObject = JSONObject.fromObject( map );   
		}
		// -------------------------------- write the bytes to the response
//		response.getOutputStream().write(xml.getBytes());
		// -------------------------------- set header info default to text/xml
		if (StringUtils.isEmpty(getContentType())) 
		{
			setContentType("text/xml;charset=euc-kr");
		}
		response.setContentType("text/xml;charset=euc-kr");
		// tell browser not to cache response
		response.setHeader("Cache-Control", "no-cache");
		
		if (isArray) {
			response.getWriter().write(jsonArray.toString().replace("null","\"\""));
		} else 	{
			response.getWriter().write("[" + jsonObject.toString().replace("null","\"\"") + "]");
		}
	}

}